﻿using Prism.Commands;
using Prism.Events;
using Prism.Services.Dialogs;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model;
using SmartPlant.Model.Biz;
using SmartPlant.Model.UI;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using System.ComponentModel;
using System.Linq;
using System.Windows.Input;

namespace SmartPlantApp.ViewModels
{
    public class PAUSelectViewModel : DialogViewModelBase, IDialogAware
    {
        private TreeNodeModelList _nodes;
        private bool _isBusy;
        private readonly BackgroundWorker backgroundWorker;

        private readonly IPlantGroupService _pauService;
        /// <summary>
        /// 事件聚合器
        /// </summary>
        private readonly IEventAggregator _eventAggregator = null;
        private DelegateCommand<object> _enterSystemCommand;
        /// <summary>
        /// 去加载PAU的API
        /// </summary>
        private DelegateCommand<object> _projectLoadCommand;
        private DelegateCommand<object> _closeWindowCommand;

        //private int _selectedIndex = 0;
        /// <summary>
        /// 选中的unit
        /// </summary>
        private PlantAreaUnit _currentSelect = null;
        //private bool _isOpen = false;

        public PAUSelectViewModel(
            IPlantGroupService plantGroupService,
            //ISysServiceInit sysServiceInit,
            IEventAggregator eventAggregator,
            IDialogService dialog) : base(dialog)
        {
            _nodes = new TreeNodeModelList();
            _nodes.SelectChanged += _nodes_SelectChanged;
            _eventAggregator = eventAggregator;
            //_sysServiceInit = sysServiceInit;
            _pauService = plantGroupService;

            backgroundWorker = new BackgroundWorker();//在 isbusy的访问器里会启动
            backgroundWorker.DoWork += this.OnBackgroundWorkerDoWork;
            backgroundWorker.RunWorkerCompleted += OnBackgroundWorkerRunWorkerCompleted;
        }

        /// <summary>
        /// 作为委托绑定到selectChange的事件上。PBS目录树的复选框勾选后
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">     </param>
        private void _nodes_SelectChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            var selectNode = _nodes.FindNodes(t => t.IsSelected == true && t.NodeType == TreeNodeType.Unit);
            var publishObj = selectNode != null ? selectNode.ToList<ITreeNodeModel>() : null;
            _eventAggregator.GetEvent<PlanSelectedEvent>().Publish(publishObj);
            GlobalObject.CurrentNodes = publishObj;
            _currentSelect = publishObj != null && publishObj.Count > 0 ? publishObj[0].Unit : null;
        }

        /// <summary>
        /// 选中的pau
        /// </summary>
        public PlantAreaUnit CurrentSelect
        {
            get { return _currentSelect; }
            set { SetProperty(ref _currentSelect, value); }
        }

        /// <summary>
        /// 当前是否处理忙碌状态。
        /// </summary>
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                if (this._isBusy != value)
                {
                    this._isBusy = value;

                    if (_isBusy && CurrentSelect == null)
                    {
                        Dialog.ShowAltert("请选择一个Unit！！！");
                        _isBusy = false;
                        return;
                    }
                    this.OnPropertyChanged(nameof(IsBusy));

                    if (this._isBusy && !backgroundWorker.IsBusy)
                    {
                        backgroundWorker.RunWorkerAsync();//在onload里绑定给了OnBackgroundWorkerDoWork
                    }
                    else
                    {
                        this._isBusy = false;
                        this.OnPropertyChanged(nameof(IsBusy));
                    }
                }
            }
        }
        /// <summary>
        /// background绑定的处理事件。RunWorkerAsync开始后触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = CurrentSelect;
        }

        /// <summary>
        /// Dowork完成后触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            InvokeOnUIThread(() =>
            {
                var result = e.Result as PlantAreaUnit;
                this.IsBusy = false;
                if (result != null)
                {
                    GlobalObject.CurrentUnit = _currentSelect;
                    _eventAggregator.GetEvent<ProjectDomainChangedEvent>().Publish(GlobalObject.CurrentProject);//发布一个事件，然后在mainWindowViewModel里去订阅了
                    RaiseRequestClose(new DialogResult(ButtonResult.OK));
                    return;
                }
                else
                {
                    Dialog.ShowAltert("选择一个Unit。");
                    _eventAggregator.GetEvent<ProjectDomainChangedEvent>().Publish(null);
                    RaiseRequestClose(new DialogResult(ButtonResult.None));
                    return;
                }
            });
        }
        /// <summary>
        /// 确定按钮，具体逻辑会跳转到IsBusy的访问器里
        /// </summary>
        public ICommand EnterSystemCommand
        {
            get
            {
                if (_enterSystemCommand != null) return _enterSystemCommand;
                _enterSystemCommand = new DelegateCommand<object>(o => this.IsBusy = true);
                return _enterSystemCommand;
            }
        }
        /// <summary>
        /// 关闭窗口
        /// </summary>
        public ICommand CloseWindowCommand
        {
            get
            {
                if (_closeWindowCommand != null) return _closeWindowCommand;
                _closeWindowCommand = new DelegateCommand<object>(o => RaiseRequestClose(new DialogResult(ButtonResult.No)));
                return _closeWindowCommand;
            }
        }

        /// <summary>
        /// loaded之后触发(绑在xaml里)
        /// </summary>
        public ICommand ProjectLoadCommand
        {
            get
            {
                if (_projectLoadCommand != null) return _projectLoadCommand;
                _projectLoadCommand = new DelegateCommand<object>(onProjectLoadCommand);
                return _projectLoadCommand;
            }
        }

        /// <summary>
        /// 调用API
        /// </summary>
        /// <param name="sender"></param>
        private async void onProjectLoadCommand(object sender)
        {
            GlobalObject.Plants = await _pauService.GetPlantGroupTreeAsync(GlobalObject.CurrentProject.ProjId.ToString());//一次够了

            TreeNodes.Clear();
            //var trees = new TreeNodeModelList();
            TreeNodes.BeginUpdate();
            foreach (var plant in GlobalObject.Plants)
            {
                var plantNode = new TreeNodeRadiolModel(TreeNodes, null)
                {
                    NodeName = plant.PlantName,
                    Id = plant.PLANT_ID.ToString(),
                    IconGlyph = "&#xe13a;",
                    NodeType = TreeNodeType.Plant
                };
                if (plant.Area != null && plant.Area.Count > 0)
                {
                    foreach (var area in plant.Area)
                    {
                        var areaNode = new TreeNodeRadiolModel(TreeNodes, plantNode)
                        {
                            NodeName = area.AreaName,
                            Id = area.AreaId.ToString(),
                            IconGlyph = "&#xe13b;",
                            NodeType = TreeNodeType.Area
                        };
                        if (area.Unit != null && area.Unit.Count > 0)
                        {
                            foreach (var unit in area.Unit)
                            {
                                var unitNode = new TreeNodeRadiolModel(TreeNodes, areaNode)
                                {
                                    NodeName = unit.UnitName,
                                    IconGlyph = "&#xe13c;",
                                    Id = unit.UnitId.ToString(),
                                    NodeType = TreeNodeType.Unit,
                                    Unit = unit
                                };
                                areaNode.Nodes.Add(unitNode);
                            }
                        }
                        plantNode.Nodes.Add(areaNode);
                    }
                }
                TreeNodes.Add(plantNode);
            }
            TreeNodes.EndUpdate();
        }

        /// <summary>
        /// 绑定到xaml里的树
        /// </summary>
        public TreeNodeModelList TreeNodes
        {
            get
            {
                return _nodes;
            }
            set { SetProperty(ref _nodes, value); }
        }
    }
}
